<template>
  <div>
    <el-row>
      <el-col :span="24" align="right">
        <el-button type="primary" @click="uploadBox()">上传附件</el-button>
      </el-col>
    </el-row>
    <Table :tableArr="fliestList" :pagination="data.page" :columns="data.columns" :isCheckbox="true"
      :total="fliestList.length" :dataSources="true">
      <template #operate="{ row }">
        <el-button size="small" type="primary" v-if="row.id" @click="handleDownload(row)">下载</el-button>
        <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
      </template>
    </Table>

    <el-dialog v-model="data.uploadDialog" append-to-body width="50%" top="10vh" :show-close="false"
      :close-on-click-modal="false">
      <template #title>
        <div class="my-header">
          <el-tabs v-model="data.activeName" class="demo-tabs">
            <el-tab-pane label="上传文件" name="first">
              <el-form :model="form" ref="ruleFormRef" :rules="rules" status-icon label-position="right" label-width="90px"
                :inline="true" class="demo-form-inline">
                <el-row>
                  <el-col :span="13">
                    <el-form-item label="文件类型" prop="busTypeName">
                      <!-- <el-select v-model="data.params.fileType" class="m-0" placeholder="请选择文件类型" size="small">
                        <el-option v-for="item in data.options" :key="item" :label="item" :value="item" />
                      </el-select> -->
                      <SelectOption :selectValue="form.busTypeName" :options="data.options" @change-value="changeValue">
                      </SelectOption>
                    </el-form-item>
                  </el-col>
                  <el-col :span="13">
                    <el-form-item label="文件">
                      <el-upload v-model:file-list="fileList" class="upload-demo" :headers="headers"
                        action="/fastDfs/file/upload" multiple :on-preview="handlePreview" :on-remove="handleRemove"
                        :before-remove="beforeRemove" :limit="3" :on-exceed="handleExceed" :on-success="handleSuccess"
                        :on-change="handleChange">
                        <el-button type="primary">上传文件</el-button>
                        <template #tip>
                          <div class="el-upload__tip">
                          </div>
                        </template>
                      </el-upload>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.uploadDialog = false">关闭</el-button>
          <el-button type="primary" @click="save()">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
        
<script lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import Table from '@/views/science/components/table/table.vue'
import SelectOption from '@/views/science/components/selectOption/index.vue'
import common from '@/views/science/common/common.json'
import { tips } from '@/views/science/components/tips/tips'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { downloadByUrl, delectFiles } from '@/views/science/api/common'
import { useStore } from 'vuex'

export default {
  components: {
    Table,
    SelectOption,
  },
  emits: {
    dataChange: null,
    filesParams: null,
  },
  props: {
    files: {
      type: Array,
      required: true,
    }
  },
  setup(props, { emit }) {
    const store = useStore()
    let data = reactive({
      activeName: ref('first'),
      columns: common.platformFileHeader,
      page: {
        page: 1,
        limit: 10,
        total: 0,
      },
      options: computed(() => store.state.technologyStrength.fileTypeList),
      uploadDialog: false,
    })

    const fliestList = ref(props.files)


    watch(props, (newValue, oldValue) => {
      fliestList.value = newValue.files
    });

    const form = reactive({
      fileName: "",
      fileSize: "",
      busTypeName: '',
      busTypeId: '',
      fileType: "",
      filePath: "",
    })

    const changeValue = (item) => {
      form.busTypeId = item.itemValue
      form.busTypeName = item.itemText
    }

    const rules = reactive({
      busTypeName: [
        { required: true, message: '请选择文件类型', trigger: 'change' },
      ]
    })

    const handleDownload = async (row) => {
      await downloadByUrl(row.fileId,row.fileName)
    }
    const handleDelete = async (row) => {
      if (row.id) {
        let res = await delectFiles(row.id)
        if (res.data.success) {
          emit('dataChange')
        }
      } else {
        var index = fliestList.value.indexOf(row);
        if (index > -1) {//大于0 代表存在，
          fliestList.value.splice(index, 1);//存在就删除
        }
      }
    }

    const uploadBox = () => {
      data.uploadDialog = true
    }

    const fileList = ref<typeof UploadUserFile[]>([])

    const handleChange: typeof UploadProps['onChange'] = (uploadFile, uploadFiles) => {
      console.log(uploadFile, uploadFiles)
      form.fileSize = uploadFile.size
      form.fileName = uploadFile.name

    }

    const handleSuccess: typeof UploadProps['onSuccess'] = (uploadFile) => {
      if (uploadFile.code == 200) {
        tips('上传成功', 'success')
        console.log(uploadFile)
        form.filePath = uploadFile.data.path
        form.fileType = uploadFile.data.type
      } else {
        tips('上传失败', 'error')
      }
    }

    const handleError: typeof UploadProps['onError'] = (uploadFile) => {
      tips('上传失败', 'error')
    }

    const handleRemove: typeof UploadProps['onRemove'] = (file, uploadFiles) => {
      console.log(file, uploadFiles)
    }

    const handlePreview: typeof UploadProps['onPreview'] = (uploadFile) => {
      console.log(uploadFile)
    }

    const beforeRemove: typeof UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
      console.log(1111)
    }

    const handleExceed: typeof UploadProps['onExceed'] = (files, uploadFiles) => {
      ElMessage.warning(
        `The limit is 3, you selected ${files.length} files this time, add up to ${files.length + uploadFiles.length
        } totally`
      )
    }

    const ruleFormRef = ref()
    const save = async () => {
      await ruleFormRef.value.validate((valid, fields) => {
        if (valid) {
          if (form.filePath) {
            let obj = {
              fileName: form.fileName,
              fileSize: form.fileSize,
              busTypeName: form.busTypeName,
              busTypeId: form.busTypeId,
              fileType: form.fileType,
              filePath: form.filePath,
            }
            if (JSON.stringify(fliestList.value).indexOf(JSON.stringify(obj)) == -1) {
              fliestList.value.push(obj)
            } else {
              tips('不可添加相同文件', 'warning')
            }

            Object.keys(form).forEach((key) => {
              form[key] = ''
            })

            fileList.value = []

            emit('filesParams', fliestList)
            data.uploadDialog = false
          } else {
            tips('上传文件不能为空', 'warning')
            // data.uploadDialog = false
          }
        } else {
          console.log('校验失败')
        }
      })

    }

    const cookie = () => localStorage.getItem('token')
    // eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsIm9yZ1R5cGUiOiJleHRlcm5hbCIsIm9yZ05hbWUiOiLkuK3lkqjmlbDmja7mnInpmZDlhazlj7giLCJjcmVhdGVkIjoxNjkzNDUwNDQ2MDUwLCJjTmFtZSI6IueuoeeQhuWRmCIsImV4cCI6MTcyNDk4NjQ0NiwidXNlcmlkIjoiNCIsInRlbmFudCI6IjEiLCJvcmdJZCI6IjEzNjMwIn0.-R5al5iis5shOri5g-afCnaMpycGAnztvkDb3WZnj9YYs-me4XhHo78OglV7fqlcLu8qDNSdkEpoGDg96gPN2w 
    return {
      data,
      form,
      fliestList,
      handleRemove,
      handlePreview,
      beforeRemove,
      handleExceed,
      rules,
      ruleFormRef,

      changeValue,
      uploadBox,
      handleDownload,
      handleDelete,
      headers: {
        Authorization: 'Bearer ' + cookie(),
      },
      handleChange,
      handleSuccess,
      handleError,
      fileList,
      save,
    }
  },
}
</script>
        
<style scoped lang="scss"></style>
        